package com.yonyougov.devops.cruxcisupport.user;

import com.yonyougov.devops.cruxcisupport.LoginInterceptor;
import com.yonyougov.devops.cruxcisupport.component.UserStore;
import com.yonyougov.devops.cruxcisupport.enums.UserOfficeTypeEnum;
import com.yonyougov.devops.cruxcisupport.user.vo.*;
import com.yonyougov.devops.cruxcisupport.userrole.UserRoleEntity;
import com.yonyougov.devops.cruxcisupport.userrole.UserRoleService;
import com.yonyougov.devops.cruxcisupport.userserver.UserServerDao;
import com.yonyougov.devops.cruxcisupport.util.JWTTokenUtil;
import com.yonyougov.devops.fwc.core.dao.BaseDao;
import com.yonyougov.devops.fwc.core.entity.Pagination;
import com.yonyougov.devops.fwc.core.service.impl.BaseServiceImpl;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.math.BigInteger;
import java.util.*;

/**
 * t_user服务实现
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<UserEntity, BigInteger> implements UserService {
    private final UserDao userDao;
    private final UserServerDao userServerDao;
    private final UserStore userStore;
    @Autowired
    private UserRoleService userRoleService;

    // token过期时间(非测试用例类型的用户)
    @Value("${token.timeout}")
    private String tokenTimeout;

    // token过期时间(测试用例类型的用户)
    @Value("${token.test-example-timeout}")
    private String testExampleTokenTimeout;

    public UserServiceImpl(UserDao userDao, UserServerDao userServerDao, UserStore userStore) {
        this.userDao = userDao;
        this.userServerDao = userServerDao;
        this.userStore = userStore;
    }

    @Override
    public BaseDao<UserEntity, BigInteger> getDao() {
        return userDao;
    }

    //<!--用户自定义代码开始-->

    /**
     * 分页模糊查询
     *
     * @param userPageLikeDto 模糊分页查询Dto
     * @return Pagination<UserPageLikeVo>
     */
    @Override
    public Pagination<UserPageLikeVo> findByPageLike(UserPageLikeDto userPageLikeDto) {
        userPageLikeDto.setLocked(false);

        List<UserPageLikeVo> userPageLikeVoList = userDao.findByPageLike(userPageLikeDto);
        int totalCount = userDao.countByLikeUser(userPageLikeDto);

        return new Pagination<UserPageLikeVo>(userPageLikeDto.getMax(), userPageLikeDto.getPageNum(), totalCount, userPageLikeVoList);
    }

    /**
     * 根据用户id查询用户公钥
     *
     * @param userId 用户id
     * @return 用户公钥(String)
     */
    @Override
    public String findPublicKeyByUserId(BigInteger userId) {
        return userDao.findPublicKeyByUserId(userId);
    }

    /**
     * 更新用户公钥
     *
     * @param userEntity
     */
    @Override
    public void updatePubKey(UserEntity userEntity) {
        String oldPublicKey = Optional.ofNullable(userDao.findBy(UserEntity.builder().id(userEntity.getId()).build())).map(UserEntity::getPublicKey).orElseGet(()-> "");
        userDao.update(userEntity);
        userServerDao.updatePubKey(oldPublicKey,userEntity);
    }

    /**
     * 获取当前用户
     *
     * @return
     */
    @Override
    public UserEntity getCurrentUser() {
        BigInteger currentUserId = userStore.getCurrentUser().getId();
        return userDao.findByPrimaryKey(currentUserId);
    }

    /**
     * 邮箱列表
     *
     * @return List<UserMailVo>
     */
    @Override
    public List<UserMailVo> mailList() {
        return userDao.mailList();
    }

    /**
     * 用户登陆
     *
     * @param userName 用户名称
     * @param password 用户密码
     * @return Map<String, Object> 结果集
     */
    @Override
    public Map<String, Object> login(String userName, String password) {
        //将密码转成MD5
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        UserEntity userEntity = UserEntity.builder()
                .userName(userName)
                .password(md5Password)
                .build();
        UserEntity result = this.findBy(userEntity);
        if (null != result) {
            if(result.getStatus()== null || result.getStatus().equals(0)){
                Map<String, Object> data = new HashMap<>();
                JwtUser jwtUser = new JwtUser();
                jwtUser.setId(result.getId());
                jwtUser.setUserName(result.getUserName());
                jwtUser.setEmail(result.getEmail());
                String token = null;
                // 如果用户身份是测试用例,token失效时间不同
                if(UserOfficeTypeEnum.TESTEXAMPLE.equals(result.getOfficeType())){
                    token = JWTTokenUtil.createJWT(jwtUser, Integer.valueOf(testExampleTokenTimeout) * 60 * 60 * 1000L, LoginInterceptor.LOGIN_KEY);
                } else {
                    token = JWTTokenUtil.createJWT(jwtUser, Integer.valueOf(tokenTimeout) * 60 * 60 * 1000L, LoginInterceptor.LOGIN_KEY);
                }
                data.put("token", token);
                data.put("user", jwtUser);
                return data;
            }
        }
        return null;
    }

    /**
     * 用户新增或更新
     *
     * @param userEntity 用户实体
     */
    @Override
    public void save(UserEntity userEntity) {
        if (null == userEntity.getId()) {
            userEntity.setCreateTime(new Date());
            userEntity.setLocked(false);
            userEntity.setPassword(DigestUtils.md5DigestAsHex(userEntity.getPassword().getBytes()));
            add(userEntity);
        } else {
            if (StringUtils.isNotBlank(userEntity.getPassword())) {
                userEntity.setPassword(DigestUtils.md5DigestAsHex(userEntity.getPassword().getBytes()));
            }
            update(userEntity);
        }
    }

    /**
     * 删除一个用户,同时删除该用户和角色的关系
     *
     * @param userEntity 用户实体
     */
    @Override
    public void deleteOneUser(UserEntity userEntity) {
        // 删除用户
        deleteByPrimaryKey(userEntity.getId());
        //删除用户和角色的关联关系
        UserRoleEntity userRoleEntity = new UserRoleEntity();
        userRoleEntity.setUserId(userEntity.getId());
        userRoleService.delete(userRoleEntity);
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return com.yonyougov.devops.cruxcisupport.user.vo.UserInfoRespVo
     */
    @Override
    public UserInfoVo findCurrentUserInfoVo() {
        // 查询当前用户信息
        UserEntity userEntity = new UserEntity();
        userEntity.setId(userStore.getCurrentUser().getId());
        userEntity = findBy(userEntity);
        // 转成前端所需要的格式
        UserInfoVo userInfoRespVo = new UserInfoVo();
        BeanUtils.copyProperties(userEntity, userInfoRespVo);
        return userInfoRespVo;
    }

    //<!--用户自定义代码结束-->
}
